﻿using Quartz.Simpl;
using Quartz.Spi;
using Quartz.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Hinacom.Scheduler
{
    public class JobStoreExFactory
    {
        private static IJobStoreExt jobStore;
        private static bool currentJobStoreIsValid = true;

        public static IJobStoreExt GetJobStoreExt()
        {
            if (jobStore == null && currentJobStoreIsValid)
            {
                string propFileName = "~/quartz.config";
                propFileName = FileUtil.ResolveFile(propFileName);
                PropertiesParser cfg = PropertiesParser.ReadFromFileResource(propFileName);

                var jobStoreTypeName = cfg.GetStringProperty("quartz.jobStore.type");
                Type jobStoreType = Type.GetType(jobStoreTypeName);
                if (jobStoreType.GetInterface("Hinacom.Scheduler.IJobStoreExt") != null)
                {
                    var delegateTypeName = cfg.GetStringProperty("quartz.jobStore.driverDelegateType");
                    var datasourceName = cfg.GetStringProperty("quartz.jobStore.dataSource");

                    jobStore = (IJobStoreExt)jobStoreType.GetConstructor(new Type[] { typeof(String), typeof(String) })
                        .Invoke(new object[] { delegateTypeName, datasourceName });
                    
                    ((IJobStore)jobStore).Initialize(new SimpleTypeLoadHelper(), null);
                }
                else
                    currentJobStoreIsValid = false;
            }
            return jobStore;
        }
    }
}
